package com.gutai.admin.common.util;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;

/**
 * 
 * 描述：阿里云对象存储服务
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID    DATE            PERSON            REASON
 *  1     2018年11月21日         YC           Create
 * ****************************************************************************
 * </pre>
 * 
 * @author YC
 * @version 1.0
 */
public class OSSUtil {

    private static final Logger logger = LoggerFactory.getLogger(OSSUtil.class);
    private static String endpoint = "oss-cn-qingdao.aliyuncs.com";
    private static String threeLevelDomain = "https://gutai-zz.oss-cn-qingdao.aliyuncs.com/";
    private static String accessKeyId = "LTAIbdqq58lKvXks";
    private static String accessKeySecret = "Oh15GyCP67sumtCjtqBSMtmxDwVK3L";

    private OSSUtil() {
        // TODO 自动生成的构造函数存根
    }

    /**
     * 
     * @param bucketName
     * @param objectKey
     * 
     * @param filePath
     * @return
     * @author YC-2018年11月21日
     */
    public static PutObjectResult putObject(String bucketName, String objectKey, String filePath) {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        PutObjectResult putObject = ossClient.putObject(bucketName, objectKey, new File(
                filePath));
        // 关闭OSSClient。
        ossClient.shutdown();
        return putObject;

    }
    public static PutObjectResult putObject(String bucketName, String objectKey, File file) {
        try {
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            PutObjectResult putObject = ossClient.putObject(bucketName,objectKey, file);
            // 关闭OSSClient。
            ossClient.shutdown();
            return putObject;
        } catch (Exception e) {
            logger.error("put object exception : {}",e );
            return null;
        }
    }

    /**
     * 生成对象在oss的URI
     * 
     * @param objectKey
     * @return
     * @author YC-2018年12月8日
     */
    public static String generateOSSURI(String objectKey) {
        StringBuilder sb = new StringBuilder(threeLevelDomain);
        sb.append(objectKey);
        return sb.toString();
    }
    public static void main(String[] args) {
        PutObjectResult putObject = OSSUtil.putObject("gutai-zz", "path/myimage.jpg",
            "F:\\jibu.jpg");

        System.out.println(putObject.getETag());
        putObject = OSSUtil.putObject("gutai-zz", "path/myimage.jpg","F:\\jibu.jpg");
        System.out.println(OSSUtil.generateOSSURI("path/myimage.jpg"));

    }

}
